package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import androidx.activity.viewModels
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.bean.old.ContractSignListToJsonBean
import com.hinnotek.amoeba.bean.old.ContractTypeAll
import com.hinnotek.amoeba.bean.old.ProductListBean
import com.hinnotek.amoeba.bean.old.ProductManagamentBean
import com.hinnotek.amoeba.databinding.ActivityContractSignBinding
import com.hinnotek.amoeba.ext.productManagementArray
import com.hinnotek.amoeba.utilities.ClickUtil
import com.hinnotek.amoeba.utilities.IntentUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.ext.productArray
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.viewmodels.ContractViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.hinnotek.amoeba.widget.EditSpinnerC
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

/**
 * 合同签署
 */
@AndroidEntryPoint
class ContractSigningActivity : BaseActivity<ActivityContractSignBinding>(), View.OnClickListener {

    private var productListBean = mutableListOf<ProductListBean>()
    private var customDialog: CustomDialog? = null

    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val contractViewModel by viewModels<ContractViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("合同签署")

        setContentView(R.layout.activity_contract_sign)
    }

    override fun initVew() {
        bindingView.etSignDate.setOnClickListener(this)
        bindingView.rbSignAddProduct.setOnClickListener(this)
        bindingView.superButtonSubmit.setOnClickListener(this)
    }

    override fun setData() {

        viewModel.getContractTypeAll().observe(this, object : ObserverState<MutableList<ContractTypeAll>>() {
            override fun onDataChange(data: MutableList<ContractTypeAll>) {
                val strings = arrayOfNulls<String>(data.size).apply {
                    for (index in data.indices) {
                        this[index] = data[index].contractTypeName
                    }
                }
                bindingView.spinnerContractType.initAdapter(strings)
                super.onDataChange(data)
            }
        })

        viewModel.getProductList()
            .observe(this, object : ObserverState<MutableList<ProductListBean>>() {
                override fun onDataChange(data: MutableList<ProductListBean>) {
                    var productId = 0
                    productListBean = data

                    bindingView.spinnerProductType.initAdapter(productArray(data))
                    bindingView.spinnerProductName.setOnItemClickListener { parent, view, position, id ->
                        productId = data[position].productId
                    }
                    viewModel.getProductTypeListByProductId(productId)
                        .observe(this@ContractSigningActivity,
                            object : ObserverState<MutableList<ProductManagamentBean>>() {
                                override fun onDataChange(data: MutableList<ProductManagamentBean>) {
                                    bindingView.spinnerProductType.initAdapter(productManagementArray(data))
                                    bindingView.spinnerProductType.setOnItemClickListener { parent, view, position, id ->
                                        val bean = data[position]
                                        val productTypePrice = bean.productPrice
                                        bindingView.etProductTypePrice.setText(productTypePrice)
                                    }
                                    super.onDataChange(data)
                                }
                            })


                    super.onDataChange(data)
                }
            })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> bindingView.etSignDate.text = data?.getStringExtra("date")
                2 -> {
                    val id: String? = data?.getStringExtra("id")
                    ToastUtils.showShort(mContext, id)
                }
            }
        }
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        val contractSignListToJsonBean = mutableListOf<ContractSignListToJsonBean>()
        when (v.id) {
            R.id.et_sign_date -> IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                1
            )
            R.id.rb_sign_add_product -> {

                val viewProduct: View = LayoutInflater.from(mContext)
                    .inflate(R.layout.include_add_product_layout, bindingView.llSignProduct, false)
                bindingView.llSignProduct.addView(viewProduct)

                val spinnerProductNameL: EditSpinnerC =
                    viewProduct.findViewById(R.id.spinner_product_name)
                val etProductTypePriceL: EditText =
                    viewProduct.findViewById(R.id.et_product_type_price)

                spinnerProductNameL.initAdapter(productArray(productListBean))
                spinnerProductNameL.setOnItemClickListener { parent, view, position, id ->
                    viewModel.getProductTypeListByProductId(productListBean[position].productId).observe(this,object :ObserverState<MutableList<ProductManagamentBean>>(){
                        override fun onDataChange(data: MutableList<ProductManagamentBean>) {
                            bindingView.spinnerProductType.initAdapter(productManagementArray(data))
                            bindingView.spinnerProductType.setOnItemClickListener { parent, view, position, id ->
                                val bean = data[position]
                                val productTypePrice = bean.productPrice
                                etProductTypePriceL.setText(productTypePrice)
                            }
                            super.onDataChange(data)
                        }

                    })

                }
                viewProduct.findViewById<View>(R.id.tv_del)
                    .setOnClickListener { v1: View? -> bindingView.llSignProduct.removeView(viewProduct) }
            }
            R.id.rb_purchase_order -> IntentUtils.startActivityForResult(
                this@ContractSigningActivity,
                RelatePurchasingListActivity::class.java,
                null,
                2
            )
            R.id.superButton_submit -> {
                val contractTypeName =
                    bindingView.spinnerContractType.editText.text.toString().trim()
                if (StringUtils.isEmpty(contractTypeName)) {
                    ToastUtils.show(mContext, "请选择合同类型")
                    return
                }

                val et_sign_unit_s = bindingView.etSignUnit.text.toString().trim()
                if (StringUtils.isEmpty(et_sign_unit_s)) {
                    ToastUtils.show(mContext, "请填写签署单位")
                    return
                }

                val et_sign_no_s = bindingView.etSignNo.text.toString().trim()
                if (StringUtils.isEmpty(et_sign_no_s)) {
                    ToastUtils.show(mContext, "请填写合同编号")
                    return
                }
                val contractSelfNo =
                    bindingView.etSignNumSub.text.toString().trim()
                if (StringUtils.isEmpty(contractSelfNo)) {
                    ToastUtils.show(mContext, "请填写合同自编号")
                    return
                }
                val signMoney =
                    bindingView.etContractMoney.text.toString().trim()
                if (StringUtils.isEmpty(signMoney)) {
                    ToastUtils.show(mContext, "请填写合同金额")
                    return
                }
                val signDate = bindingView.etSignDate.text.toString().trim()
                if (StringUtils.isEmpty(signDate)) {
                    ToastUtils.show(mContext, "请选择日期")
                    return
                }
                val projectName =
                    bindingView.etProjectName.text.toString().trim()
                if (StringUtils.isEmpty(projectName)) {
                    ToastUtils.show(mContext, "请填写项目名称")
                    return
                }
                val productName =
                    bindingView.spinnerProductName.editText.text.toString().trim()
                if (StringUtils.isEmpty(productName)) {
                    ToastUtils.show(mContext, "请选择产品名称")
                    return
                }
                val productTypeName =
                    bindingView.spinnerProductType.editText.text.toString().trim()
                if (StringUtils.isEmpty(productTypeName)) {
                    ToastUtils.show(mContext, "请选择产品类型")
                    return
                }
                val productTypePrice =
                    bindingView.etProductTypePrice.text.toString().trim()

                val productNum = bindingView.etSignNum.text.toString().trim()
                if (StringUtils.isEmpty(productNum)) {
                    ToastUtils.show(mContext, "请填写售出数量")
                    return
                }
                val customerName = bindingView.etSignUser.text.toString().trim()
                if (StringUtils.isEmpty(customerName)) {
                    ToastUtils.show(mContext, "请填写最终用户")
                    return
                }
                contractSignListToJsonBean.add(
                    ContractSignListToJsonBean(
                        projectName,
                        productName,
                        productTypeName,
                        productTypePrice,
                        productNum,
                        customerName
                    )
                )
                var i = 0
                while (i < bindingView.llSignProduct.childCount) {
                    val layout: View = bindingView.llSignProduct.getChildAt(i)
                    val etProjectNameV: EditText = layout.findViewById(R.id.et_project_name)
                    val spinnerProductNameV: EditSpinnerC = layout.findViewById(R.id.spinner_product_name)
                    val editSpinnerC: EditSpinnerC = layout.findViewById(R.id.spinner_product_type)
                    val etProductTypePriceV: EditText = layout.findViewById(R.id.et_product_type_price)
                    val etSignNumV: EditText = layout.findViewById(R.id.et_sign_num)
                    val etSignUserV: EditText = layout.findViewById(R.id.et_sign_user)
                    val etProjectNameVS = etProjectNameV.text.toString().trim()
                    if (StringUtils.isEmpty(etProjectNameVS)) {
                        ToastUtils.show(mContext, "请填写项目名称")
                        return
                    }
                    val spinnerProductNameVS =
                        spinnerProductNameV.editText.text.toString().trim()
                    if (StringUtils.isEmpty(spinnerProductNameVS)) {
                        ToastUtils.show(mContext, "请选择产品名称")
                        return
                    }
                    val spinnerProductTypeVS =
                        editSpinnerC.editText.text.toString().trim()
                    if (StringUtils.isEmpty(spinnerProductTypeVS)) {
                        ToastUtils.show(mContext, "请选择产品类型")
                        return
                    }
                    val etProductTypePriceVS = etProductTypePriceV.text.toString().trim()
                    val etSignNumVS = etSignNumV.text.toString().trim()
                    if (StringUtils.isEmpty(etSignNumVS)) {
                        ToastUtils.show(mContext, "请填写签署数量")
                        return
                    }
                    val etSignUserVS =
                        etSignUserV.text.toString().trim()
                    if (StringUtils.isEmpty(etSignUserVS)) {
                        ToastUtils.show(mContext, "请填写最终用户")
                        return
                    }
                    contractSignListToJsonBean.add(
                        ContractSignListToJsonBean(
                            etProjectNameVS,
                            spinnerProductNameVS,
                            spinnerProductTypeVS,
                            etProductTypePriceVS,
                            etSignNumVS,
                            etSignUserVS
                        )
                    )
                    i++
                }
                val contractSignListToJson = Gson().toJson(contractSignListToJsonBean)
                addCompanyContract(
                    contractTypeName,
                    et_sign_unit_s,
                    et_sign_no_s,
                    contractSelfNo,
                    signDate,
                    signMoney,
                    contractSignListToJson
                )
            }
        }
    }

    /**
     * app端添加合同接口
     */
    fun addCompanyContract(
        contractTypeName: String, signUnit: String, contractNo: String, contractSelfNo: String,
        signDate: String, signMoney: String, companyContractProjectJson: String
    ) {
        customDialog = CustomDialog(mContext, "正在加载...")
        customDialog?.show()

        val map = mutableMapOf<String,Any>().apply {
            put("createUser", SharedPreUtils.getString("userName"))
            put("contractTypeName", contractTypeName)
            put("signUnit", signUnit)
            put("contractNo", contractNo)
            put("contractSelfNo", contractSelfNo)
            put("signDate", signDate)
            put("signMoney", signMoney)
            put("companyContractProjectJson", companyContractProjectJson)
        }
        contractViewModel.addCompanyContract(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog?.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog?.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })

    }
}